<?php

namespace Beerus\Modules\WikiRanking\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Biz\cache\wiki\WikiRanking as cacheWikiRanking;
use Biz\model\wiki\ObjRelateWiki as mObjRelateWiki;
use Biz\model\wiki\Wiki as mWiki;
use Biz\model\wiki\WikiRankingBrand;
use Biz\model\wiki\WikiRankingCateHotUp;
use Biz\model\wiki\WikiRankingCatePublic;
use Biz\model\wiki\WikiRankingConfig as mWikiRankingConfig;
use Biz\model\wiki\WikiRankingHot;
use Biz\model\wiki\WikiRankingPublicPraise;
use Biz\model\wiki\WikiRankingWeek;
use Biz\service\wikiRanking\AdmRanking;
use Biz\service\wikiRanking\Ranking;
use Doraemon\model\Blank as DbBlank;
use Doraemon\model\Member;
use Doraemon\model\Photos as DbPhotos;
use Doraemon\service\User;
use Doraemon\service\Videos\Videos;
use Doraemon\tools\BlockType;
use Doraemon\tools\Hhzurl;
use Doraemon\tools\IdParse;
use Doraemon\tools\ImgUrl;
use Biz\model\wiki\WikiRankingPic;
use Doraemon\tools\Log;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;
use Biz\model\wiki\Wiki;


class CheckRankingController extends Controller
{

    const TYPE_ARR = [
        ['type' => 1, 'name' => '热度榜'],
        ['type' => 2, 'name' => '口碑榜'],
        ['type' => 3, 'name' => '品牌榜'],
        ['type' => 4 , 'name' => '热度飙升榜'],
        ['type' => 5 , 'name' => '住友口碑榜']
    ];

    const BRAND_TYPE_DEFAULT = 0;
    const BRAND_TYPE_EXPIRE = 1;
    const BRAND_TYPE_COMMON = 2;
    const BRAND_TYPE_BEST = 3;
    const BRAND_TYPE_SUPER = 4;
    const BRAND_TYPE = [
        AdmRanking::BRAND_TYPE_EXPIRE => '到期品牌',
        AdmRanking::BRAND_TYPE_COMMON => '普通认证品牌',
        AdmRanking::BRAND_TYPE_BEST => '精选品牌',
        AdmRanking::BRAND_TYPE_SUPER => '超级品牌',
    ];

    const HOT_UP_TYPE =  4;
    const HOT_UP_ID = 10000;
    const PUBLIC_UP_TYPE = 5;
    const PUBLIC_UP_ID = 10001;

    public function __construct()
    {
        parent::__construct();
        Admin::script('$(".pjax-container").attr("id","pjax-container");');
    }

    /*list
     * */
    public function list(Request $request, Content $content)
    {

        $pageSize = $request->input("per_page", 20);
        $page = $request->input("page", 1);
        $requestParams['page_size'] = $pageSize;
        $requestParams['page'] = $page;


        $list = WikiRankingWeek::getList($pageSize, $page);
        $total = WikiRankingWeek::count();
        $gridModel = new pGridDataModel($list, $total, [
            'perPage' => $pageSize
        ]);
        $gridList = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel) {
                $grid->disableExport();
                $grid->disableFilter();
                $grid->disableRowSelector();
                $grid->disableColumnSelector();
                $grid->disablePagination();
                $grid->disableCreateButton();
                $grid->column('id');
                $grid->column('ranking_day', '榜单号')->display(function () {
                    $hot_type = self::HOT_UP_TYPE;
                    $format = [];
                    $format[] = "<a href='/admin/wikiRanking/checkRank/rankList/{$this->ranking_day}'>{$this->ranking_day}</a>";
                    $format[] = "<a href='/admin/wikiRanking/checkCateRank/{$this->ranking_day}/{$hot_type}'>全品类{$this->ranking_day}</a>";

                    return $format;
                })->label('default');
                $grid->disableActions();

            });

        return $content->header('榜单审核管理')->row($gridList);
    }


    /**
     * 榜单管理
     * @param Request $request
     * @param Content $content
     * @param $ranking_day
     * @param string $firstRank
     * @param string $secondRank
     * @param string $type
     * @return Content
     */
    public function rankList(
        Request $request,
        Content $content,
                $ranking_day,
                $firstRank = '',
                $secondRank = '',
                $type = ''
    )
    {
        Admin::script($this->setScript());
        Admin::script($this->checkScript());

        $rankingList = mWikiRankingConfig::selectByWhere([
            'pid' => 0,
            'config_state[!]' => mWikiRankingConfig::CONFIG_STATE_DEL,
            'ORDER' => ['sort' => 'ASC']
        ]);
        $ids = $rankingList ? array_column($rankingList, 'id') : [];
        $hashRankingList = array_combine(array_column($rankingList, 'id'), $ids);

        if ($firstRank == '') {
            $firstRank = $rankingList[0]['id'];
        }
        $secondList = [];
        $rankingId = 0;
        if ($ids) {
            $secondArr = mWikiRankingConfig::selectByWhere([
                'pid' => $ids,
                'config_state' => mWikiRankingConfig::CONFIG_STATE_SHOW
            ]);
            foreach ($secondArr as $row) {
                if ($row['id'] == $secondRank) {
                    $rankingId = $row['id'];
                }
                $secondList[$row['pid']][] = $row;
            }
        }
        if ($secondRank == '') {
            $secondRank = $secondList[$hashRankingList[$firstRank]][0]['id'];
            $rankingId = $secondList[$hashRankingList[$firstRank]][0]['id'];
        }
        if ($type == '') {
            $type = AdmRanking::TYPE_ARR[0]['name'];
        }
        $tab = new Tab();
        foreach ($rankingList as $firstRanking) {
            $childTab = new Tab();
            if (isset($secondList[$firstRanking['id']]) && $secondList[$firstRanking['id']]) {
                foreach ($secondList[$firstRanking['id']] as $secondRanking) {
                    //三级
                    $thirdChild = new Tab();
                    foreach (AdmRanking::TYPE_ARR as $val_type) {
                        if ($firstRanking['id'] === $firstRank && $secondRanking['id'] === $secondRank && $val_type['name'] === $type) {
                            $thirdChild->add($val_type['name'], $this->getList($ranking_day, $rankingId, $type ,$firstRank), true);
                        } else {
                            $thirdChild->addLink($val_type['name'],
                                url('/admin/wikiRanking/checkRank/rankList/' . $ranking_day . '/' . $firstRanking['id'] . "/" . $secondRanking['id'] . "/" . $val_type['name']));
                        }
                    }
                    //二级
                    if ($secondRanking['id'] === $secondRank) {
                        $childTab->add($secondRanking['id'] . "-" . $secondRanking['ranking_name'], $thirdChild, true);
                    } else {
                        $childTab->add($secondRanking['id'] . "-" . $secondRanking['ranking_name'], $thirdChild);
                    }
                }
            }
            //一级
            if ($firstRanking['id'] === $firstRank) {
                $tab->add($firstRanking['id'] . '-' . $firstRanking['ranking_name'], $childTab, true);
            } else {
                $tab->add($firstRanking['id'] . '-' . $firstRanking['ranking_name'], $childTab);
            }
        }

        Admin::html("<input  type='hidden' class='rankingDay' value='" . $ranking_day . "'>");
        Admin::html("<input  type='hidden' class='rankType' value='" . $type . "'>");
        Admin::html("<input  type='hidden' class='secondRank' value='" . $secondRank . "'>");
        Admin::html("<input  type='hidden' class='firstRank' value='" . $firstRank . "'>");


        $content->row($tab);
        return $content
            ->header('第' . $ranking_day . '期榜单')
            ->description(' ')
            ->breadcrumb(['text' => '榜单审核', 'url' => url('/admin/wikiRanking/checkRank/index')], ['text' => '']);
    }

    /**
     * 榜单列表
     * @param $ranking_day
     * @param $rankingId
     * @param $type
     * @return string
     */
    public function getList($ranking_day, $rankingId, $type ,$first_rank = 0)
    {
        $map = [
            'AND' => [
                'ranking_id' => $rankingId,
                'ranking_state' => [
                    WikiRankingBrand::RANKING_STATE_NORMAL,
                    WikiRankingBrand::RANKING_STATE_SHOW,
                    WikiRankingBrand::RANKING_STATE_HIDE
                ],
                'ranking_day' => $ranking_day,
            ],
            'ORDER' => ['score' => 'DESC'],
            'LIMIT' => 40
        ];
        $lastMap = [];
        $rankingCover = [];
        $today = date('Ymd');
        $day = Ranking::getRankingDay();
        $lastInfo = WikiRankingWeek::getByWhere(['ORDER' => ['ranking_day' => 'DESC']]);
        $lastDay = $lastInfo['ranking_day'];
        if ($lastDay > $today && $ranking_day > $today) {
            $lastMap = [
                'ranking_state' => [WikiRankingBrand::RANKING_STATE_SHOW],
                'ranking_day' => $day,
                'ranking_id' => $rankingId,
            ];
        }
        if ($type == '品牌榜') {
            $list = WikiRankingBrand::getListByWhere($map);
            $list = AdmRanking::formateBrandList($list, $lastMap);
        }
        if ($type == "热度榜") {
            $list = WikiRankingHot::getListByWhere($map);
            $list = AdmRanking::formateHotList($list, $lastMap);
            $rankingCover = Ranking::getHotRankingCover($ranking_day,$rankingId);
        }
        if ($type == "口碑榜") {
            $list = WikiRankingPublicPraise::getListByWhere($map);
            $list = AdmRanking::formatePublicPraiseList($list, $lastMap);
        }
        if ($list && is_array($list)) {
            foreach ($list as $key => &$val) {
                $val['top'] = $key + 1;
                $val['wiki_id'] = $val['wiki_info']['id'];
            }
        }

        $gridModel = new pGridDataModel($list, 40);
        $listGrid = Admin::grid($gridModel, function (Grid $grid) use ($type, $ranking_day ,$first_rank,$rankingCover) {
            $grid->disableCreateButton();
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->disableFilter();
            $grid->disablePagination();
            $grid->column('top', '排名');

            if ($type == "热度榜") {
                $grid->column('cover_img', 'Wiki信息')->width(200)->display(function () use ($type, $ranking_day) {

                    $imgPath = $this->cover_img;
                    $html = strlen($imgPath) ? "<img src='" . $imgPath . "' style='width:100px' class='img img-thumbnail' />" : "";
                    $html .= "<br/><span>" . $this->basic_title . "</span>";
                    $html .= "<br/>basic_id:" . $this->basic_id;
                    //待审核
                    if ($this->ranking_state == WikiRankingHot::RANKING_STATE_NORMAL) {
                        $html .= '<a href="javascript:;" class=" editRank" data-type="edit-basic"   data-id="' . $this->id . '"  data-rank="' . $type . '"  data-day="' . $this->ranking_day . '">更换</a><br/>';
                        if (empty($this->wiki_id)) {
                            $html .= "<span style='color:#de0c0c'>(未绑定wiki_id)<span>";
                        } else {
                            $html .= '<a href="/admin/wiki/admList/' . $this->wiki_id . '/edit" target="_blank">编辑wiki</a>';
                        }
                    }
                    //待审核
                    $html .= '<br/><a class="fa fa-envelope" href="javascript:layer.open({
                                type: 2,
                                title: \'预览\',
                                maxmin: true,
                                area: [\'1000px\', \'650px\'],
                                content: \'' . $this->h5_wiki_url . '\'
                            });">预览</a>';
                    return $html;
                });
                $grid->column('score', '得分')->display(function () use ($type) {
                    $html = $this->score;
                    //待审核
                    if ($this->ranking_state == WikiRankingHot::RANKING_STATE_NORMAL) {
                        $html .= '<a href="javascript:;" class=" editRank" data-type="edit-score"   data-id="' . $this->id . '"  data-rank="' . $type . '"  data-day="' . $this->ranking_day . '">编辑></a>';
                    }
                    //待审核
                    //if ($this->continue_week) {
                    $html .= '<br/>截止到' . $this->last_ranking_day . '连续上榜：<span style="color: green;font-size: 40px" >' . $this->continue_week . '</span>次';
                    //}
                    return $html;
                });


                //wiki img
                $grid->column('wiki_img',"榜单卡片背景图")->display(function () use ($type, $ranking_day,$first_rank) {
                    if ($this->wiki_img) {
                        $html = strlen($this->wiki_img) ? "<img src='" . $this->wiki_img . "' style='width:100px' class='img img-thumbnail' /><br/>" : "";

                        $html .= "<a href='javascript:;' class='fa fa-upload  uploadBasicPic'  data-type='$type'    data-id='$this->id' data-basic='$this->basic_id'  data-first='$first_rank'>更换</a> &nbsp;&nbsp;&nbsp;&nbsp;";
                        $html .= '<a class=\'fa fa-trash trashBasicPic\' data-basic="' . $this->basic_id . '" data-type="' . $type . '"  data-ranking_day ="' . $this->row['ranking_day'] . '" >删除</a>';
                    } else {
                        $html = "<a href='javascript:;' class='fa fa-upload  uploadBasicPic' data-type='$type' data-id='$this->id'  data-basic='$this->basic_id' data-first='$first_rank'>上传</a>";

                    }

                    return $html;
                });
                //wiki img

                $grid->column('brand_id', '所属品牌')->display(function () {
                    $html = strlen($this->brand_logo) ? "<img src='" . $this->brand_logo . "' style='width:100px' class='img img-thumbnail' />" : "";
                    $html .= $this->brand_name;
                    if ($this->brand_type) {
                        $html .= "(" . $this->brand_type . ")";
                    }
                    return $html;
                })->width(100);


            } elseif ($type == "口碑榜") {

                $grid->column('cover_img', 'Wiki信息')->width(200)->display(function () use ($type, $ranking_day) {
                    $imgPath = $this->cover_img;
                    $html = strlen($imgPath) ? "<img src='" . $imgPath . "' style='width:100px' class='img img-thumbnail' />" : "";
                    $html .= "<br/><span>" . $this->basic_title . "</span>";
                    $html .= "<br/>basic_id:" . $this->basic_id;
                    //待审核
                    if ($this->ranking_state == WikiRankingHot::RANKING_STATE_NORMAL) {
                        $html .= '<a href="javascript:;" class=" editRank" data-type="edit-basic"   data-id="' . $this->id . '"  data-rank="' . $type . '"  data-day="' . $this->ranking_day . '">更换</a><br/>';
                        if (empty($this->wiki_id)) {
                            $html .= "<span style='color:#de0c0c'>(未绑定wiki_id)<span>";
                        } else {
                            $html .= '<a href="/admin/wiki/admList/' . $this->wiki_id . '/edit" target="_blank">编辑wiki</a>';
                        }
                    }
                    //待审核
                    $html .= '<br/><a class="fa fa-envelope" target="_blank" href="' . $this->h5_wiki_url . '">预览</a>';
                    return $html;
                });

                $grid->column('brand_id', '品牌信息')->display(function () {
                    $html = strlen($this->brand_logo) ? "<img src='" . $this->brand_logo . "' style='width:100px' class='img img-thumbnail' />" : "";
                    $html .= $this->brand_name;
                    if ($this->brand_type) {
                        $html .= "(" . $this->brand_type . ")";
                    }
                    return $html;
                })->width(100);
                $grid->column('score', '得分')->display(function () use ($type) {
                    $html = $this->score;
                    //待审核
                    if ($this->ranking_state == WikiRankingHot::RANKING_STATE_NORMAL) {
                        $html .= '<a href="javascript:;" target="_blank" class=" editRank" data-type="edit-score"   data-id="' . $this->id . '"  data-rank="' . $type . '"  data-day="' . $this->ranking_day . '">编辑></a>';
                    }
                    //待审核
                    //if ($this->continue_week) {
                    $html .= '<br/>截止到' . $this->last_ranking_day . '连续上榜：<span style="color: green;font-size: 40px" >' . $this->continue_week . '</span>次';
                    // }
                    return $html;
                });
                //wiki img
                $grid->column('wiki_img',"榜单卡片背景图")->display(function () use ($type, $ranking_day,$first_rank) {
                    if ($this->wiki_img) {
                        $html = strlen($this->wiki_img) ? "<img src='" . $this->wiki_img . "' style='width:100px' class='img img-thumbnail' /><br/>" : "";

                        $html .= "<a href='javascript:;' class='fa fa-upload  uploadBasicPic'  data-type='$type'    data-id='$this->id' data-basic='$this->basic_id'  data-first='$first_rank'>更换</a> &nbsp;&nbsp;&nbsp;&nbsp;";
                        $html .= '<a class=\'fa fa-trash trashBasicPic\' data-basic="' . $this->basic_id . '" data-type="' . $type . '"  data-ranking_day ="' . $this->row['ranking_day'] . '" >删除</a>';
                    } else {
                        $html = "<a href='javascript:;' class='fa fa-upload  uploadBasicPic' data-type='$type' data-id='$this->id'  data-basic='$this->basic_id' data-first='$first_rank'>上传</a>";

                    }

                    return $html;
                });
                //wiki img



                $grid->column('conent_desc', '精选口碑')->display(function () use ($type, $ranking_day) {
                    if ($this->obj_id) {
                        if ($this->obj_type == BlockType::TYPE_PHOTO) {
                            $desc = "图片note";
                        } else {
                            $desc = "文章";
                        }
                        $html = '<P>ID:' . $this->obj_id . '</P>';
                        $html .= $desc . ":<p style='text-overflow:ellipsis;overflow: hidden;white-space: nowrap;width: 200px'>" . $this->content_desc . "</p>";
                        $html .= strlen($this->content_pic) ? "<img src='" . $this->content_pic . "' style='width:100px' class='img img-thumbnail' /><br/>" : "";

                        $html .= '<a class="fa fa-envelope" href="javascript:layer.open({
                                type: 2,
                                title: \'预览\',
                                maxmin: true,
                                area: [\'1000px\', \'650px\'],
                                content: \'' . $this->h5_note_url . '\'
                            });">预览</a><br/>';


                    } else {
                        $html = "<p>无数据</p>";
                    }
                    //待审核
                    if ($this->ranking_state == WikiRankingHot::RANKING_STATE_NORMAL) {
                        $html .= '<a href="javascript:;" class=" editRank" data-type="edit-note"   data-id="' . $this->id . '"  data-rank="' . $type . '"  data-day="' . $this->ranking_day . '">编辑</a></br>';
                        $html .= '<a href="javascript:;" class=" editNote" data-type="edit-note"   data-id="' . $this->id . '"  data-rank="' . $type . '"  data-day="' . $this->ranking_day . '">更换内容</a>';
                    }
                    //待审核
                    return $html;
                });

            } elseif ($type == "品牌榜") {
                $grid->column('brand_id', '品牌信息')->display(function () use ($ranking_day, $type) {
                    $html = strlen($this->brand_logo) ? "<img src='" . $this->brand_logo . "' style='width:100px' class='img img-thumbnail' />" : "";
                    $html .= $this->brand_name;
                    if ($this->brand_type) {
                        $html .= "(" . $this->brand_type . ")";
                    }
                    return $html;
                })->width(100);
                $grid->column('score', '得分')->display(function () use ($type) {
                    $html = $this->score;
                    //待审核
                    if ($this->ranking_state == WikiRankingHot::RANKING_STATE_NORMAL) {
                        $html .= '<a href="javascript:;" class=" editRank" data-type="edit-score"   data-id="' . $this->id . '"  data-rank="' . $type . '"  data-day="' . $this->ranking_day . '">编辑></a>';
                    }
                    //待审核
                    //if ($this->continue_week) {
                    $html .= '<br/>截止到' . $this->last_ranking_day . '连续上榜：<span style="color: green;font-size: 40px" >' . $this->continue_week . '</span>次';
                    //}
                    return $html;
                });
                $grid->column('cover_img', 'Wiki信息')->width(200)->display(function () use ($type) {
                    $imgPath = $this->cover_img;
                    $html = strlen($imgPath) ? "<img src='" . $imgPath . "' style='width:100px' class='img img-thumbnail' />" : "";
                    $html .= "<br/><span>" . $this->basic_title . "</span>";
                    $html .= "<br/>basic_id:" . $this->basic_id;
                    //待审核
                    if ($this->ranking_state == WikiRankingHot::RANKING_STATE_NORMAL) {
                        $html .= '<a href="javascript:;" class=" editRank" data-type="edit-basic"   data-id="' . $this->id . '"  data-rank="' . $type . '"  data-day="' . $this->ranking_day . '">更换</a><br/> ';
                        if (empty($this->wiki_id)) {
                            $html .= "<span style='color:#de0c0c'>(未绑定wiki_id)<span>";
                        } else {
                            $html .= '<a href="/admin/wiki/admList/' . $this->wiki_id . '/edit" target="_blank">编辑wiki</a>';
                        }
                    }
                    //待审核
                    $html .= '<br/><a class="fa fa-envelope" href="javascript:layer.open({
                                type: 2,
                                title: \'预览\',
                                maxmin: true,
                                area: [\'1000px\', \'650px\'],
                                content: \'' . $this->h5_wiki_url . '\'
                            });">预览</a>';
                    return $html;
                });

            }

            $grid->column("ranking_state", '榜单状态')->display(function () {
                if ($this->ranking_state == WikiRankingBrand::RANKING_STATE_NORMAL) {
                    return "<span style='color:#00c0ef'>待发榜</span>";
                }
                if ($this->ranking_state == WikiRankingBrand::RANKING_STATE_HIDE) {
                    return "<span style='color:#dd4b39'>未上榜</span>";
                }
                if ($this->ranking_state == WikiRankingBrand::RANKING_STATE_SHOW) {
                    return "<span style='color:#00a65a'> 上榜中</span>";
                }
            });

            $grid->actions(function (Grid\Displayers\Actions $actions) use ($type,$rankingCover) {
                $actions->disableEdit();
                $actions->disableDelete();

                $actions->append('<a class=\'fa fa-trash trash-rank\' data-id="' . $this->row["id"] . '" data-type="' . $type . '"  data-ranking_day ="' . $this->row['ranking_day'] . '" >踢出榜单</a>');

                if($type == '热度榜' && $this->row['top'] <= 20 ) {

                    if(!empty($rankingCover) && $rankingCover['hot_ranking_id'] == $this->row["id"]) {
                        $actions->append('<a class=\'fa fa-chevron-left set-rank-cover\' style="margin-left:15px;cursor:pointer;color:red;" data-is_set_cover="true" data-id="' . $this->row["id"] . '" data-type="' . $type . '"  data-ranking_day ="' . $this->row['ranking_day'] . '" >取消榜单封面设置</a>');
                    }else{
                        $actions->append($rankingCover['hot_ranking_id'].'<a class=\'fa fa-chevron-right set-rank-cover\' style="margin-left:15px;cursor:pointer;" data-is_set_cover="false" data-id="' . $this->row["id"] . '" data-type="' . $type . '"  data-ranking_day ="' . $this->row['ranking_day'] . '" >设为榜单封面</a>');
                    }

                }

            });
        });
        $list = $listGrid->render();
        return $list;
    }


    public function editBasic(Request $request, \App\Admin\Extensions\WorkContent $content, $ranking_day, $id, $type)
    {
        $date_type = $request->input('type', '');
        $code = $request->input('code', 0);
        if ($code == 1) {
            $script = <<<SCRIPT
            setTimeout(function () {
                        parent.window.location.reload();
                    }, 1000);
SCRIPT;
            Admin::script($script);
        }
        $map = [
            'id' => $id,
            'ranking_day' => $ranking_day,
        ];
        if ($type == '品牌榜') {
            $list = WikiRankingBrand::getByWhere($map);
        }
        if ($type == "热度榜") {
            $list = WikiRankingHot::getByWhere($map);;
        }
        if ($type == "口碑榜") {
            $list = WikiRankingPublicPraise::getByWhere($map);;
        }
        if($type == self::HOT_UP_TYPE){
            $list = WikiRankingCateHotUp::getByWhere($map);
            $list['percent'] = $list['up_percent'];
        }
        if($type == self::PUBLIC_UP_TYPE){
            $list = WikiRankingCatePublic::getByWhere( $map);
        }


        $list['type'] = $type;
        $list['data-type'] = $date_type;
        // Admin::style('.main-header {display:none;}');
        $form = new Form($list);
        $form->hidden('id');
        $form->hidden('type');
        if ($date_type == 'edit-note') {
            $form->text('obj_id', '内容id')->required();
        }
        if ($date_type == 'edit-basic') {
            $form->text('basic_id', 'basic_id')->required();
        }
        if ($date_type == 'edit-score') {
            $form->text('score', '得分')->required();
        }
        if ($date_type == 'edit-percent') {
            $form->text('percent', '百分比')->required();
        }
        $form->hidden('data-type', 'data-type');
        $form->disableReset();
        $form->action('/admin/wikiRanking/checkRank/postedit');
        return $content
            ->body($form);
    }

    public function editNote(Request $request, \App\Admin\Extensions\WorkContent $content, $id)
    {
        $script = <<<SCRIPT
            $('.checkNote').unbind('click').click(function() {
                var id = $(this).data('id');
                var objId = $(this).data('objid');
                var dateType = $(this).data('type');
                console.log(id);
                console.log(objId);
                let url = '/admin/wikiRanking/checkRank/postNote';
                let params = {id:id,obj_id:objId ,type:dateType};
                $.post(url, params , function (result) {
                    if (result.code == 1) {
                        layer.msg(result.message);
                        setTimeout(function () {
                            parent.window.location.reload();
                        }, 1000);
                    } else {
                        layer.msg(result.message);
                    }
                });
		});
SCRIPT;
        Admin::script($script);
        $params = $request->all();
        $datatype = $params['type'] ? : 3;
        if($params['type'] == self::PUBLIC_UP_TYPE){
            $info = WikiRankingCatePublic::getByWhere(['id' => $id]);
        }else{
            $info = WikiRankingPublicPraise::getByWhere(['id' => $id]);

        }
        if ($info && $info['basic_id']) {
            $wikiInfo = mWiki::getByWhere([
                'status[!]' => mWiki::STATUS_DELETE,
                'basic_id' => $info['basic_id'],
                'is_default' => 1
            ]);
            $wikiId = $wikiInfo ? $wikiInfo['id'] : 0;
            if ($wikiId) {
                $objIds = mObjRelateWiki::getByWhere([
                    'wiki_id' => $wikiId,
                    'obj_type' => [mObjRelateWiki::OBJ_TYPE_NOTE, mObjRelateWiki::OBJ_TYPE_BLANK],
                    'status' => mObjRelateWiki::STATUS_NORMAL
                ], 'obj_id');
                $list = [];
                $noteIds = [];
                $blankIds = [];
                $uids = [];
                foreach ($objIds as $objId) {
                    $type = IdParse::getType($objId);
                    switch ($type) {
                        case BlockType::TYPE_PHOTO:
                        case BlockType::TYPE_ANSWER:
                            $noteIds[] = $objId;
                            $uid = IdParse::getUid($objId);
                            $uids[] = $uid;
                            $list[] = ['obj_id' => $objId, 'type' => $type, 'uid' => $uid];
                            break;
                        case BlockType::TYPE_BLANK:
                            $blankIds[] = $objId;
                            $list[] = ['obj_id' => $objId, 'type' => $type, 'uid' => $uid];
                            break;
                    }
                }
                $userList = User::getBatchBasicUserInfo($uids);
                $userList = array_column($userList, null, 'uid');
                $noteList = [];
                $blankList = [];
                if ($noteIds) {
                    $dbData = DbPhotos::getPhotos($noteIds);
                    foreach ($dbData as $row) {
                        $row['pic_url'] = '';
                        if ($row['pic_id']) {
                            $row['pic_url'] = ImgUrl::getUrl(ImgUrl::APPTYPE_APP, $row["pic_id"],
                                ImgUrl::IMAGE_SIZE_SQ_PHONE);
                        } else {
                            if ($row['video_id']) {
                                $videoInfo = Videos::GetCanUseVideosById($row['video_id']);
                                $picId = $videoInfo ? $videoInfo['cover_pic_id'] : '';
                                $row['pic_url'] = $picId ? ImgUrl::getUrl(ImgUrl::APPTYPE_APP, $picId,
                                    ImgUrl::IMAGE_SIZE_SQ_PHONE) : '';
                            }
                        }
                        $noteList[$row['id']] = $row;
                    }
                }
                if ($blankIds) {
                    $dbData = DbBlank::getBatchBlankByIds($blankIds);
                    foreach ($dbData as $row) {
                        $row['pic_url'] = ImgUrl::getUrl(ImgUrl::APPTYPE_APP, $row['cover_pic_id'],
                            ImgUrl::IMAGE_SIZE_ORI_NPHONE);
                        $blankList[$row['bid']] = $row;
                    }
                }
                $modelList = [];
                foreach ($list as $row) {
                    switch ($row['type']) {
                        case BlockType::TYPE_PHOTO:
                            $row['title'] = $noteList ? $noteList[$row['obj_id']]['title'] : '';
                            $row['cover_img'] = $noteList ? $noteList[$row['obj_id']]['pic_url'] : '';
                            $row['remark'] = $noteList ? $noteList[$row['obj_id']]['remark'] : '';
                            $row['link'] = Hhzurl::h5PhotoShow($row['obj_id']);
                            break;
                        case BlockType::TYPE_BLANK:
                            $row['title'] = $blankList ? $blankList[$row['obj_id']]['title'] : '';
                            $row['cover_img'] = $blankList ? $blankList[$row['obj_id']]['pic_url'] : '';
                            $row['remark'] = $blankList ? $blankList[$row['obj_id']]['remark'] : '';
                            $row['link'] = Hhzurl::h5BlankShow($row['obj_id']);
                            break;
                    }
                    $modelList[] = $row;
                }
                $gridModel = new pGridDataModel($modelList);
                $gridList = Admin::grid($gridModel,
                    function (Grid $grid) use ($gridModel, $id, $userList ,$datatype) {
                        $grid->disableCreateButton();
                        $grid->disablePagination();
                        $grid->disableFilter();
                        $grid->disableExport();
                        $grid->disableRowSelector();
                        $grid->column('obj_id', 'ID')->display(function () use ($id , $datatype) {
                            $html = $this->obj_id;
                            $html .= '<a href="javascript:void(0);" class="fa fa-check checkNote"   data-type="' . $datatype . '" data-objid="' . $this->obj_id . '" data-id="' . $id . '">选择</a>';
                            return $html;
                        });
                        $grid->column('type', '类型')->display(function () {
                            return ($this->type == BlockType::TYPE_PHOTO) ? 'note' : '文章';
                        });
                        $grid->column('cover_img', '点击图片预览详情')->width(200)->display(function () {
                            $imgPath = $this->cover_img;
                            $image = strlen($imgPath) ? "<a href='" . $this->link . "' target='_blank'><img src='" . $imgPath . "' style='width:80px' class='img img-thumbnail' /></a>" : "";
                            return $image;
                        });
                        $grid->column('uid', '用户信息')->display(function () use ($userList) {
                            $userInfo = isset($userList[$this->uid]) ? $userList[$this->uid] : [];
                            $imgPath = $userInfo ? $userInfo['avatar'] : '';
                            $html = strlen($imgPath) ? "<img src='" . $imgPath . "' style='width:50px' class='img img-thumbnail' />" : "";
                            $html .= "<br/><span>" . ($userInfo ? $userInfo['nick'] : "") . "</span>";
                            $html .= "<br/>uid:" . $this->uid;
                            if ($userInfo) {
                                $html .= "<br/><span>" . Member::$typeDesc[$userInfo['type']] . "</span>";
                            }
                            return $html;
                        });
                        $grid->column('remark', '描述');
                        $grid->disableActions();
                        $grid->actions(function (Grid\Displayers\Actions $actions) {
                            $actions->disableEdit();
                            $actions->disableView();
                            $actions->disableDelete();
                            $actions->append('<a href="javascript:void(0);" class="fa fa-check checkNote" data-id="' . $this->row['obj_id'] . '">选择</a>');
                        });
                    }
                );
                return $content->header('选择住有说')->row($gridList->render());
            }
        }
        return $content->header('选择住有说')->row('没有任务数据');
    }
    /*添加精选
      *
      * */
    public function postedit(Request $request)
    {
        $request = $request->all();
        $id = $request['id'];
        $score = $request['score'] ?: 0;
        $percent = $request['percent'] ? : 0;
        $basic_id = $request['basic_id'] ?: 0;
        $obj_id = $request['obj_id'] ?: '';
        $type = $request['type'] ?: '';
        $data_type = $request['data-type'] ?: '';
        $map = [
            'id' => $id,
        ];
        if($basic_id){
            $wikiInfo =  Wiki::getInfoByBasicId($basic_id);
        }
        if ($type == '品牌榜') {
            $list = WikiRankingBrand::getByWhere($map);
        }
        if ($type == "热度榜") {
            $list = WikiRankingHot::getByWhere($map);;
        }
        if ($type == "口碑榜") {
            $list = WikiRankingPublicPraise::getByWhere($map);;
        }
        if($type == self::HOT_UP_TYPE){
            $list = WikiRankingCateHotUp::getByWhere($map);
        }
        if($type == self::PUBLIC_UP_TYPE){
            $list = WikiRankingCatePublic::getByWhere( $map);
        }

        if (empty($list)) {
            return response()->json(['stauts' => false, 'message' => '内容不存在']);
        }
        $data = [];
        if ($data_type == 'edit-basic') {
            $data['basic_id'] = $basic_id;
        }
        if ($data_type == 'edit-score') {
            $data['score'] = $score;
        }
        if ($data_type == 'edit-note') {
            $data['obj_id'] = $obj_id;
            $obj_type = IdParse::getType($obj_id);
            $data['obj_type'] = $obj_type;
        }
        if ($data_type == 'edit-percent') {
           $data['up_percent'] = $percent;
        }
        if ($type == '品牌榜') {
            $result = WikiRankingBrand::updateData($data, $map);
        }
        if ($type == "热度榜") {
            $result = WikiRankingHot::updateData($data, $map);
        }
        if ($type == "口碑榜") {
            $result = WikiRankingPublicPraise::updateData($data, $map);
        }
        if($type == self::HOT_UP_TYPE){
            if($wikiInfo && is_array($wikiInfo) ){
                $data['brand_id'] = $wikiInfo['brand_id'] ? : 0;
            }
            $result = WikiRankingCateHotUp::updateData($data , $map);
        }
        if($type == self::PUBLIC_UP_TYPE){
            if($wikiInfo && is_array($wikiInfo) ){
                $data['brand_id'] = $wikiInfo['brand_id'] ? : 0;
            }
            $result = WikiRankingCatePublic::updateData($data , $map);
        }
        $success = new MessageBag([
            'title' => '操作成功'
        ]);
        return redirect('/admin/wikiRanking/checkRank/editBasic/' . $list['ranking_day'] . '/' . $list['id'] . '/' . $type . '?code=1&type=' . $data_type)->with(compact('success'));
    }

    public function postNote(Request $request)
    {
        $request = $request->all();
        $id = $request['id'];
        $objId = $request['obj_id'];
        if (!$id || !$objId) {
            return response()->json([
                'status' => false,
                'message' => "操作失败,参数错误",
            ]);
        }
        $datatype = $request['type'];
        if($datatype == self::PUBLIC_UP_TYPE){
            $info = WikiRankingCatePublic::getByWhere(['id' => $id]);
        }else{
            $info = WikiRankingPublicPraise::getByWhere(['id' => $id]);
        }
        if ($info) {
            $objType = IdParse::getType($objId);
            if($datatype == self::PUBLIC_UP_TYPE){
                $result = WikiRankingCatePublic::updateData([
                    'obj_id' => $objId,
                    'obj_type' => $objType,
                ], ['id' => $id]);
            }else{
                $result = WikiRankingPublicPraise::updateData([
                    'obj_id' => $objId,
                    'obj_type' => $objType,
                    'is_changed_obj' => 1
                ], ['id' => $id]);

            }

        } else {
            return response()->json([
                'status' => false,
                'message' => "操作失败,不存在的信息",
            ]);
        }
        if ($result) {
            return response()->json([
                'code' => 1,
                'message' => "操作成功",
            ]);
        } else {
            return response()->json([
                'status' => false,
                'message' => "操作失败",
            ]);
        }
    }

    public function delRankList(Request $request, Content $content, $ranking_day, $id = 0, $type)
    {
        $currRankingDay = Ranking::getRankingDay();
        if ($ranking_day < $currRankingDay) {
            return response()->json([
                'status' => false,
                'message' => "操作失败，往期榜单不支持操作",
            ]);
        }
        $map = [
            'id' => $id,
            'ranking_day' => $ranking_day,
        ];
        if ($type == '品牌榜') {
            $info = WikiRankingBrand::getByWhere(['id' => $id]);
            $result = WikiRankingBrand::updateData(['ranking_state' => WikiRankingBrand::RANKING_STATE_DEL, 'top_num' => 0], $map);
            if ($info && $info['top_num']) {//如果正在当期榜单，并且上榜中，踢出某一个榜单，其后边儿的榜单排名都提升一名
                $rankingId = $info['ranking_id'];
                $topNum = $info['top_num'];
                if ($ranking_day == $currRankingDay) {
                    cacheWikiRanking::delBrandCache($ranking_day, $info['brand_id']);
                }
                $list = WikiRankingBrand::selectByWhere(['ranking_day' => $ranking_day, 'ranking_id' => $rankingId, 'top_num[>]' => $topNum, 'ORDER' => ['top_num' => 'ASC']]);
                foreach ($list as $row) {
                    $topNum = $row['top_num'] - 1;
                    $where = [
                        'ranking_id' => $row['ranking_id'],
                        'ranking_day' => $ranking_day,
                        'brand_id' => $row['brand_id']
                    ];
                    $data = [
                        'top_num' => $topNum
                    ];
                    if ($topNum <= 20 && $ranking_day == $currRankingDay) {
                        cacheWikiRanking::addBrandRanking($ranking_day, $row['brand_id'], $topNum, $rankingId);
                        //$data['ranking_state'] = WikiRankingBrand::RANKING_STATE_SHOW;
                    }
                    WikiRankingBrand::updateData($data, $where);
                }
            }
        } else if ($type == "热度榜") {
            $info = WikiRankingHot::getByWhere(['id' => $id]);
            $result = WikiRankingHot::updateData(['ranking_state' => WikiRankingHot::RANKING_STATE_DEL, 'top_num' => 0], $map);;
            if ($info && $info['top_num']) {//如果正在当期榜单，并且上榜中，踢出某一个榜单，其后边儿的榜单排名都提升一名
                $rankingId = $info['ranking_id'];
                $topNum = $info['top_num'];
                if ($ranking_day == $currRankingDay) {
                    cacheWikiRanking::delHotCache($ranking_day, $info['basic_id']);
                }
                $list = WikiRankingHot::selectByWhere(['ranking_day' => $ranking_day, 'ranking_id' => $rankingId, 'top_num[>]' => $topNum, 'ORDER' => ['top_num' => 'ASC']]);
                foreach ($list as $row) {
                    $topNum = $row['top_num'] - 1;
                    $where = [
                        'ranking_id' => $row['ranking_id'],
                        'ranking_day' => $ranking_day,
                        'basic_id' => $row['basic_id']
                    ];
                    $data = [
                        'top_num' => $topNum
                    ];
                    if ($topNum <= 20 && $ranking_day == $currRankingDay) {
                        cacheWikiRanking::addBasicWikiHotRanking($ranking_day, $row['basic_id'], $topNum, $rankingId);
                        //$data['ranking_state'] = WikiRankingHot::RANKING_STATE_SHOW;
                    }
                    WikiRankingHot::updateData($data, $where);
                }
            }
        } else if ($type == "口碑榜") {
            $info = WikiRankingPublicPraise::getByWhere(['id' => $id]);
            $result = WikiRankingPublicPraise::updateData(['ranking_state' => WikiRankingPublicPraise::RANKING_STATE_DEL, 'top_num' => 0], $map);
            if ($info && $info['top_num']) {//如果正在当期榜单，并且上榜中，踢出某一个榜单，其后边儿的榜单排名都提升一名
                $rankingId = $info['ranking_id'];
                $topNum = $info['top_num'];
                if ($ranking_day == $currRankingDay) {
                    cacheWikiRanking::delPublicPraiseCache($ranking_day, $info['basic_id']);
                }
                $list = WikiRankingPublicPraise::selectByWhere(['ranking_day' => $ranking_day, 'ranking_id' => $rankingId, 'top_num[>]' => $topNum, 'ORDER' => ['top_num' => 'ASC']]);
                foreach ($list as $row) {
                    $topNum = $row['top_num'] - 1;
                    $where = [
                        'ranking_id' => $row['ranking_id'],
                        'ranking_day' => $ranking_day,
                        'basic_id' => $row['basic_id']
                    ];
                    $data = [
                        'top_num' => $topNum
                    ];
                    if ($topNum <= 20 && $ranking_day == $currRankingDay) {
                        cacheWikiRanking::addBasicWikiPublicPraiseRanking($ranking_day, $row['basic_id'], $topNum, $rankingId);
                        //$data['ranking_state'] = WikiRankingPublicPraise::RANKING_STATE_SHOW;
                    }
                    WikiRankingPublicPraise::updateData($data, $where);
                }
            }
        }elseif($type == self::HOT_UP_TYPE){
            $info = WikiRankingCateHotUp::getByWhere(['id' => $id]);
            $result = WikiRankingCateHotUp::updateData(['ranking_state' => WikiRankingHot::RANKING_STATE_DEL, 'top_num' => 0], $map);;
            if ($info && $info['top_num']) {//如果正在当期榜单，并且上榜中，踢出某一个榜单，其后边儿的榜单排名都提升一名
                $rankingId = self::HOT_UP_ID;
                $topNum = $info['top_num'];
                if ($ranking_day == $currRankingDay) {
                    cacheWikiRanking::delHotUpCache($ranking_day, $info['basic_id']);
                }
                $list = WikiRankingCateHotUp::selectByWhere(['ranking_day' => $ranking_day, 'top_num[>]' => $topNum, 'ORDER' => ['top_num' => 'ASC']]);
                foreach ($list as $row) {
                    $topNum = $row['top_num'] - 1;
                    $where = [
                        'ranking_day' => $ranking_day,
                        'basic_id' => $row['basic_id']
                    ];
                    $data = [
                        'top_num' => $topNum
                    ];
                    if ($topNum <= 10 && $ranking_day == $currRankingDay) {
                        cacheWikiRanking::addBasicWikiHotUpRanking($ranking_day, $row['basic_id'], $topNum, $rankingId);
                        //$data['ranking_state'] = WikiRankingHot::RANKING_STATE_SHOW;
                    }
                    WikiRankingCateHotUp::updateData($data, $where);
                }
            }

        }elseif($type == self::PUBLIC_UP_TYPE){
            $info = WikiRankingCatePublic::getByWhere(['id' => $id]);
            $result = WikiRankingCatePublic::updateData(['ranking_state' => WikiRankingPublicPraise::RANKING_STATE_DEL, 'top_num' => 0], $map);
            if ($info && $info['top_num']) {//如果正在当期榜单，并且上榜中，踢出某一个榜单，其后边儿的榜单排名都提升一名
                $rankingId = self::PUBLIC_UP_ID;
                $topNum = $info['top_num'];
                if ($ranking_day == $currRankingDay) {
                    cacheWikiRanking::delCatePublicCache($ranking_day, $info['basic_id']);
                }
                $list = WikiRankingPublicPraise::selectByWhere(['ranking_day' => $ranking_day, 'top_num[>]' => $topNum, 'ORDER' => ['top_num' => 'ASC']]);
                foreach ($list as $row) {
                    $topNum = $row['top_num'] - 1;
                    $where = [
                        'ranking_day' => $ranking_day,
                        'basic_id' => $row['basic_id']
                    ];
                    $data = [
                        'top_num' => $topNum
                    ];
                    if ($topNum <= 10 && $ranking_day == $currRankingDay) {
                        cacheWikiRanking::addBasicWikiCatePublicRanking($ranking_day, $row['basic_id'], $topNum, $rankingId);
                        //$data['ranking_state'] = WikiRankingPublicPraise::RANKING_STATE_SHOW;
                    }
                    WikiRankingCatePublic::updateData($data, $where);
                }
            }
        }
        if ($result) {
            Ranking::setShowRankingIds();
            return response()->json([
                'code' => 1,
                'message' => "操作成功",
            ]);
        } else {
            return response()->json([
                'status' => false,
                'message' => "操作失败",
            ]);
        }
    }


    //添加评论弹窗
    public function basicPic(Request $request, \App\Admin\Extensions\WorkContent $content, $basic_id)
    {
        $request = $request->all();
        return $content
            ->header('上传')
            ->body(self::uploadBasicPic($request, $basic_id));
    }

    public function uploadBasicPic($request, $basic_id)
    {
        $info =  WikiRankingPic::getByWhere(['basic_id' => $basic_id]);
        $info['basic_id'] = $basic_id;
        if($info['pic_status'] == WikiRankingPic::STATUS_DELETE){
            $info['basic_pic_id'] = '';
        }
        $form = new Form($info);
        $form->hidden('id');
        $form->hidden('basic_id');
        $form->imgUpload("basic_pic_id" , "榜单wiki图片",false);
        $form->action('/admin/wikiRanking/checkRank/saveBasicPic');
        return $form->render();
    }



    //添图片
    public function saveBasicPic(Request $request)
    {
        $request = $request->all();
        $basic_id = $request['basic_id'];
        $basic_pic_id = $request['basic_pic_id'];
        $id =  $request['id'];
        if($request['basic_id']){
        }
        $data = [
            'basic_id' =>$basic_id,
            'basic_pic_id' => $basic_pic_id,
            'admin_id' => Admin::user()->id,
            'pic_status' => WikiRankingPic::STATUS_NORMAL
        ];
        if($id){
            $result = WikiRankingPic::updateData($data , ['id' =>$id]);

        }else{
           $result =  WikiRankingPic::insertData($data);
        }

        // 返回结果
        if ($result) {
            $ranking_day = Ranking::getRankingDay();
            WikiRankingHot::updateData(['basic_pic_id' => $basic_pic_id] , ['ranking_day[>=]' => $ranking_day , 'basic_id' => $basic_id ]);

            WikiRankingPublicPraise::updateData(['basic_pic_id' => $basic_pic_id] , ['ranking_day[>=]' => $ranking_day , 'basic_id' => $basic_id ]);
            WikiRankingCateHotUp::updateData(['basic_pic_id' => $basic_pic_id] , ['ranking_day[>=]' => $ranking_day , 'basic_id' => $basic_id ]);

            WikiRankingCatePublic::updateData(['basic_pic_id' => $basic_pic_id] , ['ranking_day[>=]' => $ranking_day , 'basic_id' => $basic_id ]);

            $success = new MessageBag([
                'title' => '上传成功'
            ]);
            return redirect('/admin/wikiRanking/checkRank/basicPic/'.$basic_id)->with(compact('success'));
        } else {
            $error = new MessageBag([
                'title' => '评论失败'
            ]);
           // return redirect('/admin/blank/select/comment/' . $data['obj_id'])->with(compact('error'));
        }
    }


    //添图片
    public function trashBasicPic(Request $request , $basic_id)
    {
        $info = WikiRankingPic::getByWhere(['basic_id' => $basic_id]);
        $data = [
            'basic_id' =>$basic_id,
            'admin_id' => Admin::user()->id,
            'pic_status' => WikiRankingPic::STATUS_DELETE
        ];
        $result = WikiRankingPic::updateData($data , ['id' =>$info['id']]);
        // 返回结果
        if ($result) {
            $ranking_day = Ranking::getRankingDay();
            WikiRankingHot::updateData(['basic_pic_id' => ''] , ['ranking_day[>=]' => $ranking_day , 'basic_id' => $basic_id ]);
            WikiRankingPublicPraise::updateData(['basic_pic_id' => ''] , ['ranking_day[>=]' => $ranking_day , 'basic_id' => $basic_id ]);
            WikiRankingCateHotUp::updateData(['basic_pic_id' => ''] , ['ranking_day[>=]' => $ranking_day , 'basic_id' => $basic_id ]);

            WikiRankingCatePublic::updateData(['basic_pic_id' => ''] , ['ranking_day[>=]' => $ranking_day , 'basic_id' => $basic_id ]);

            return response()->json([
                'code' => 1,
                'message' => "操作成功",
            ]);
        } else {
            return response()->json([
                'code' => 0,
                'message' => "操作失败",
            ]);
        }
    }




    /**
     * 榜单管理
     * @param Request $request
     * @param Content $content
     * @param $ranking_day
     * @param string $firstRank
     * @param string $secondRank
     * @param string $type
     * @return Content
     */
    public function cateRankList(
        Request $request,
        Content $content,
        $day,
        $type = self::HOT_UP_TYPE
    )
    {
        $ranking_day=$day;
        Admin::script('$(".pjax-container").attr("id","pjax-container");');
        Admin::script($this->checkScript());
        if(self::HOT_UP_TYPE ==$type){
            $list =  WikiRankingCateHotUp::getListByWhere(
                [
                     'ranking_day' => $ranking_day,
                    'ranking_state' => [WikiRankingCateHotUp::RANKING_STATE_SHOW , WikiRankingCateHotUp::RANKING_STATE_NORMAL ,WikiRankingCateHotUp::RANKING_STATE_HIDE],
                    'ORDER'=>['score' => "DESC" , 'up_percent' => 'DESC','id' => 'ASC'],
                    'LIMIT' => [0 , 60]
                ]
            );
            $ranking_id = self::HOT_UP_ID;
            $list = AdmRanking::formateHotList($list ,[]);
        }elseif(self::PUBLIC_UP_TYPE ==$type){
            $list =  WikiRankingCatePublic::getListByWhere(
                [
                     'ranking_day' => $ranking_day,
                    'ranking_state' => [WikiRankingCateHotUp::RANKING_STATE_SHOW , WikiRankingCateHotUp::RANKING_STATE_NORMAL,WikiRankingCateHotUp::RANKING_STATE_HIDE],
                    'ORDER'=>['score' => "DESC" ],
                    'LIMIT' => [0 , 60]
                ]
            );
            $ranking_id = self::PUBLIC_UP_ID;
            $list = AdmRanking::formatePublicPraiseList($list , []);
        }


        if ($list && is_array($list)) {
            foreach ($list as $key => &$val) {
                $val['top'] = $key + 1;
                $val['wiki_id'] = $val['wiki_info']['id'];
                $val['ranking_id'] = $ranking_id;
            }
        }
        $gridModel = new pGridDataModel($list, 60);
        $gridList = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel ,$ranking_day , $type ) {
                $grid->disableCreateButton();
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->disableFilter();
                $grid->disablePagination();
                $grid->column('top', '排名');
                $grid->column('cover_img', 'Wiki信息')->width(200)->display(function () use ( $ranking_day , $type) {

                    $imgPath = $this->cover_img;
                    $html = strlen($imgPath) ? "<img src='" . $imgPath . "' style='width:100px' class='img img-thumbnail' />" : "";
                    $html .= "<br/><span>" . $this->basic_title . "</span>";
                    $html .= "<br/>basic_id:" . $this->basic_id;
                    //待审核
                    if ($this->ranking_state == WikiRankingHot::RANKING_STATE_NORMAL) {
                        $html .= '<a href="javascript:;" class=" editRank" data-type="edit-basic"   data-id="' . $this->id . '"  data-rank="' . $type . '"  data-day="' . $this->ranking_day . '">更换</a><br/>';
                        if (empty($this->wiki_id)) {
                            $html .= "<span style='color:#de0c0c'>(未绑定wiki_id)<span>";
                        } else {
                            $html .= '<a href="/admin/wiki/admList/' . $this->wiki_id . '/edit" target="_blank">编辑wiki</a>';
                        }
                    }
                    //待审核
                    $html .= '<br/><a class="fa fa-envelope" href="javascript:layer.open({
                                type: 2,
                                title: \'预览\',
                                maxmin: true,
                                area: [\'1000px\', \'650px\'],
                                content: \'' . $this->h5_wiki_url . '\'
                            });">预览</a>';
                    return $html;
                });
                $grid->column('score', '得分')->display(function () use ($type) {
                    $html = $this->score;
                    //待审核
                    if ($this->ranking_state == WikiRankingHot::RANKING_STATE_NORMAL) {
                        $html .= '<a href="javascript:;" class=" editRank" data-type="edit-score"   data-id="' . $this->id . '"  data-rank="' . $type . '"  data-day="' . $this->ranking_day . '">编辑></a><br/>';
                       if($type == self::HOT_UP_TYPE){
                           $html .= $this->up_percent.'%<a href="javascript:;" class=" editRank" data-type="edit-percent"   data-id="' . $this->id . '"  data-rank="' . $type . '"  data-day="' . $this->ranking_day . '">编辑></a>';
                       }
                    }
                    //待审核
                    //if ($this->continue_week) {
                    $html .= '<br/>截止到' . $this->last_ranking_day . '连续上榜：<span style="color: green;font-size: 40px" >' . $this->continue_week . '</span>次';
                    //}
                    return $html;
                });

                //wiki img
                $grid->column('wiki_img',"榜单卡片背景图")->display(function () use ($type, $ranking_day) {
                    if ($this->wiki_img) {
                        $html = strlen($this->wiki_img) ? "<img src='" . $this->wiki_img . "' style='width:100px' class='img img-thumbnail' /><br/>" : "";

                        $html .= "<a href='javascript:;' class='fa fa-upload  uploadBasicPic'  data-type='$type'    data-id='$this->id' data-basic='$this->basic_id' >更换</a> &nbsp;&nbsp;&nbsp;&nbsp;";
                        $html .= '<a class=\'fa fa-trash trashBasicPic\' data-basic="' . $this->basic_id . '" data-type="' . $type . '"  data-ranking_day ="' . $this->row['ranking_day'] . '" >删除</a>';
                    } else {
                        $html = "<a href='javascript:;' class='fa fa-upload  uploadBasicPic' data-type='$type' data-id='$this->id'  data-basic='$this->basic_id'  >上传</a>";

                    }
                    return $html;
                });
                //wiki img
                $grid->column('brand_id', '所属品牌')->display(function () {
                    $html = strlen($this->brand_logo) ? "<img src='" . $this->brand_logo . "' style='width:100px' class='img img-thumbnail' />" : "";
                    $html .= $this->brand_name;
                    if ($this->brand_type) {
                        $html .= "(" . $this->brand_type . ")";
                    }
                    return $html;
                })->width(100);

                if($type == self::PUBLIC_UP_TYPE){
                    $grid->column('conent_desc', '精选口碑')->display(function () use ($type, $ranking_day) {
                        if ($this->obj_id) {
                            if ($this->obj_type == BlockType::TYPE_PHOTO) {
                                $desc = "图片note";
                            } else {
                                $desc = "文章";
                            }
                            $html = '<P>ID:' . $this->obj_id . '</P>';
                            $html .= $desc . ":<p style='text-overflow:ellipsis;overflow: hidden;white-space: nowrap;width: 200px'>" . $this->content_desc . "</p>";
                            $html .= strlen($this->content_pic) ? "<img src='" . $this->content_pic . "' style='width:100px' class='img img-thumbnail' /><br/>" : "";

                            $html .= '<a class="fa fa-envelope" href="javascript:layer.open({
                                type: 2,
                                title: \'预览\',
                                maxmin: true,
                                area: [\'1000px\', \'650px\'],
                                content: \'' . $this->h5_note_url . '\'
                            });">预览</a><br/>';


                        } else {
                            $html = "<p>无数据</p>";
                        }
                        //待审核
                        if ($this->ranking_state == WikiRankingHot::RANKING_STATE_NORMAL) {
                            $html .= '<a href="javascript:;" class=" editRank" data-type="edit-note"   data-id="' . $this->id . '"  data-rank="' . $type . '"  data-day="' . $this->ranking_day . '">编辑</a></br>';
                            $html .= '<a href="javascript:;" class=" editNote" data-type="edit-note"   data-id="' . $this->id . '"  data-rank="' . $type . '"  data-day="' . $this->ranking_day . '">更换内容</a>';
                        }
                        //待审核
                        return $html;
                    });
                }
                $grid->column("ranking_state", '榜单状态')->display(function () {
                    if ($this->ranking_state == WikiRankingBrand::RANKING_STATE_NORMAL) {
                        return "<span style='color:#00c0ef'>待发榜</span>";
                    }
                    if ($this->ranking_state == WikiRankingBrand::RANKING_STATE_HIDE) {
                        return "<span style='color:#dd4b39'>未上榜</span>";
                    }
                    if ($this->ranking_state == WikiRankingBrand::RANKING_STATE_SHOW) {
                        return "<span style='color:#00a65a'> 上榜中</span>";
                    }
                });

                $grid->actions(function (Grid\Displayers\Actions $actions) use ($type) {
                    $actions->disableEdit();
                    $actions->disableDelete();

                    $actions->append('<a class=\'fa fa-trash trash-rank\' data-id="' . $this->row["id"] . '" data-type="' . $type . '"  data-ranking_day ="' . $this->row['ranking_day'] . '" >踢出榜单</a>');
                });

            }
        );

        $tab = new Tab();

        if($type == self::HOT_UP_TYPE){
            $tab->add('热度飙升榜', $gridList->render(), true);
            $tab->addLink('住友口碑榜', url('/admin/wikiRanking/checkCateRank/'.$ranking_day."/".self::PUBLIC_UP_TYPE));

        }else{
            $tab->addLink('热度飙升榜', url('/admin/wikiRanking/checkCateRank/'.$ranking_day."/".self::HOT_UP_TYPE));
            $tab->add('住友口碑榜', $gridList->render() , true);
        }
        $content->row($tab);
        return $content
            ->header('第' . $ranking_day . '期榜单')
            ->description(' ')
            ->breadcrumb(['text' => '榜单审核', 'url' => url('/admin/wikiRanking/checkRank/index')], ['text' => '']);



    }









        /*设置scirpt
        *
        * */
    private function setScript()
    {
        return <<<SCRIPT
         $('.nav-tabs li').click(function(e){
              var name=e.target.innerText;
              var index  = name.indexOf("-");
              tab_name = name.substr(0, index)
              var isfirst = lifirst(tab_name)
              var day = $('.rankingDay').val();
              if(isfirst){
                     parent.window.location.replace('/admin/wikiRanking/checkRank/rankList/'+day+'/'+tab_name)
              }else{
                   var firstname = li();
                   var isthird =  lithird(name);
                   if(!isthird){
                       var type = $('.rankType').val();
                       parent.window.location.replace('/admin/wikiRanking/checkRank/rankList/'+day+'/'+firstname+'/'+tab_name);
                   }
              }
        })
        
       function li(){
                 var list = $('.nav-tabs:nth(0)').children();
                 for (var i = 0; i < list.length; i++) {
                   if( list[i].className == 'active'){
                    var list_index = list[i].innerText.indexOf("-");
                    var list_name = list[i].innerText.substr(0,list_index)
                    return list_name
                   }
                 }
       }
       
       function lifirst(name){
          var list = $('.nav-tabs:nth(0)').children();
             for (var i = 0; i < list.length; i++) {
                var list_index = list[i].innerText.indexOf("-");
                var list_name = list[i].innerText.substr(0, list_index)
                   if(name != '' && list_name == name){
                        console.log(name)
                        return true
                   }
             }
             return false
       }
       
       function lithird(name){
           if( name == '口碑榜' || name == '热度榜' || name == '品牌榜'){
                return true
           }
           return false
       }
SCRIPT;
    }



    private function checkScript()    {
        return <<<SCRIPT
       $('.trash-rank').unbind('click').click(function(){
            var id= $(this).data('id');
            var ranking_day = $(this).data('ranking_day');
            var type = $(this).data('type')
            layer.confirm('确定要踢出榜单么？', {
                btn: ['确定', '取消']
            }, function (index) {
                layer.close(index);
                 let url = '/admin/wikiRanking/checkRank/delRankList/'+ ranking_day+'/'+id+'/'+type;
                let params = {};
                $.post(url, params , function (result) {
                    if (result.code == 1) {
                        layer.msg(result.message);
                        setTimeout(function () {
                            parent.window.location.reload();
                        }, 2000);
                    } else {
                        layer.msg(result.message);
                    }
                });
            });
        })
        
        $('.trashBasicPic').unbind('click').click(function(){
            var basic_id = $(this).data('basic');
            layer.confirm('确定要删除图片么？', {
                btn: ['确定', '取消']
            }, function (index) {
                layer.close(index);
                 let url = '/admin/wikiRanking/checkRank/trashBasicPic/'+basic_id;
                let params = {};
                $.post(url, params , function (result) {
                    if (result.code == 1) {
                        layer.msg(result.message);
                        setTimeout(function () {
                            parent.window.location.reload();
                        }, 2000);
                    } else {
                        layer.msg(result.message);
                    }
                });
            });
        })
        
        
        
        $('.uploadBasicPic').unbind('click').click(function() {
                var basic_id = $(this).data('basic');
                var id = $(this).data('id');
                var type = $(this).data('type');
                var first_rank = $(this).data('first');
                //iframe窗
                layer.open({
                    type: 2,
                    title: '上传',
                    shadeClose: true,
                    shade: 0.4,
                    maxmin: true,
                    area: ['700px', '600px'],
                    content: '/admin/wikiRanking/checkRank/basicPic/'+basic_id,
                    end: function () {
                       parent.window.location.reload();
                    }
                   
                });
		    });
        
         $('.editRank').unbind('click').click(function() {
            var id = $(this).data('id');
            var dataType=$(this).data('type');
            var rankingtype = $(this).data('rank');
            var day = $(this).data('day')
            layer.open({
                type: 2,
                title: '编辑',
                shadeClose: true,
                shade: 0,
                maxmin: true,
                area: ['300px', '300px'],
                content: '/admin/wikiRanking/checkRank/editBasic/'+day+'/'+id+'/'+rankingtype+'?type='+dataType,
            });
		});
		
		$('.editNote').unbind('click').click(function() {
            var id = $(this).data('id');
            var dataType=$(this).data('type');
            var rankingtype = $(this).data('rank');
            var day = $(this).data('day')
            layer.open({
                type: 2,
                title: '住有说',
                shadeClose: true,
                shade: 0,
                maxmin: true,
                area: ['1000px', '650px'],
                content: '/admin/wikiRanking/checkRank/editNote/'+id+'?type='+rankingtype,
            });
		});
		
		//设置为榜单封面或取消
		$('.set-rank-cover').unbind('click').click(function(){
            var id= $(this).data('id');
            var is_set_cover = $(this).data('is_set_cover') ? 0 : 1;
            var op_text_arr = ['取消设置为榜单封面','设置为榜单封面'];
            layer.confirm('确定要'+op_text_arr[is_set_cover]+'？', {
                btn: ['确定', '取消']
            }, function (index) {
                layer.close(index);
                let url = '/admin/wikiRanking/checkRank/setRankingCover/'+ id;
                let params = {
                   set_cover: is_set_cover
                };
                $.post(url, params , function (result) {
                    if (result.code == 1) {
                        layer.msg(result.message);
                        setTimeout(function () {
                            parent.window.location.reload();
                        }, 2000);
                    } else {
                        layer.msg(result.message);
                    }
                });
            });
        })
        

SCRIPT;
    }

public function setRankingCover(Request $request,$id){

    $params = $request->all();

    $isSetCover = $params['set_cover'] ?? 0;

    try {

        $wikiRankingHotInfo = WikiRankingHot::get('*', ['id' => $id]);

        if(empty($wikiRankingHotInfo)){
            throw new \Exception('参数错误');
        }

        if($isSetCover){

            if(in_array($wikiRankingHotInfo['ranking_state'],[WikiRankingHot::RANKING_STATE_HIDE,WikiRankingHot::RANKING_STATE_DEL])){
                throw new \Exception('未上榜或已删除');
            }

            if (!Ranking::setHotRankingCover($id)) {
                throw new \Exception('设置排行榜封面失败');
            }
            return response()->json([
                'code' => 1,
                'message' => "操作成功",
            ]);
        }

        //取消排行榜封面设置
        $rankingCover = Ranking::getHotRankingCover(
            $wikiRankingHotInfo['ranking_day'],
            $wikiRankingHotInfo['ranking_id']
        );

        if(!empty($rankingCover)){
            $hot_ranking_id = $rankingCover['hot_ranking_id'];
            if($id != $hot_ranking_id){
                throw new \Exception('禁止操作');
            }
            Ranking::delHotRankingCover(
                $wikiRankingHotInfo['ranking_day'],
                $wikiRankingHotInfo['ranking_id']
            );
        }

        return response()->json([
            'code' => 1,
            'message' => "操作成功",
        ]);


    }catch (\Exception $e){

        Log::error('set-ranking-cover-fail',['id' => $id, 'error' => $e->getMessage()]);

        return response()->json([
            'code' => 0,
            'message' => "操作失败",
        ]);
    }

}

}
